﻿//function , like C# string.format(parms1,pamrs2,....) or using string.format(parmsArray)
String.prototype.format = function (parms1, parms2) {
    var pattern = /\{\d+\}/g;

    var arrParms = arguments;
    if (arguments.length == 1 && arguments[0] instanceof Array) {
        arrParms = arguments[0];
    }
    return this.replace(pattern, function () { return arrParms[parseInt(arguments[0].substring(1))]; });
}

//Class StringBuffer, like stringbulider in C#
function StringBuilder() {
    this.__strings__ = new Array;
}

StringBuilder.prototype.append = function (str) {
    this.__strings__.push(str);
}

StringBuilder.prototype.appendFormat = function (str, parms1, parms2) {
    var pattern = /\{\d+\}/g;

    var arrParms = arguments;
    if (arguments.length == 2 && arguments[1] instanceof Array) {
        arrParms = arguments[1];
        arrParms.unshift("");
    }

    this.__strings__.push(str.replace(pattern, function () { return arrParms[parseInt(arguments[0].substring(1)) + 1]; }));
}

StringBuilder.prototype.toString = function () {
    return this.__strings__.join("");
}

//local namespace
function local() { };
local._debugObject = null;



//***************************************************
// MessageBox related
//***************************************************
local.mesagebox = function () {
}
local.mesagebox.defaultTitle = '错误提示';
local.mesagebox.defaultWidth = 360;
local.mesagebox.showError = function (msg) {
    $('<div></div>')
                    .html("<div class='server_msg'>" + msg + "</div>")
                    .dialog({
                        autoOpen: true,
                        title: local.mesagebox.defaultTitle,
                        show: 'slide',
                        modal: true,
                        width: local.mesagebox.defaultWidth,
                        buttons: {
                            "确定": function () { $(this).dialog('close'); }
                        }
                    });
}

//***************************************************
// Rate related function
//***************************************************
local.rate = function () { };
local.rate.click = function (obj, type) {
    var objs = $(obj).parentsUntil(".lite-rate").parent();
    var hidInput = $(obj).siblings(":hidden")[0];
    hidInput.value = type;
    objs.removeClass().addClass("lite-rate lite-rate" + type);
}
local.rate.mouseout = function (obj) {
    var objs = $(obj).parentsUntil(".lite-rate").parent();
    var hidInput = $(obj).siblings(":hidden")[0];
    objs.className = "lite-rate" + (hidInput.value == 0 ? "" : (" lite-rate" + hidInput.value));
}
local.rate.mouseover = function (obj, type) {
    var objs = $(obj).parentsUntil(".lite-rate").parent().removeClass().addClass("lite-rate lite-rate" + type);
}

//***************************************************
// google map related 
//***************************************************
local.gmap = function () {
}

/// <summary>
/// 创建一个google.maps.Map对象，并将其返回 
/// </summary>
/// <param name="mapCanvas" type="jQuery,dom object">地图容器，比如一个Div</param>
/// <param name="centerPoint" type="LatLng">地图中心位置</param>
local.gmap.createMap = function (mapCanvas, centerPoint) {
    var options = {
        zoom: 14,
        center: centerPoint,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: true,
        streetViewControl: true,
        //disableDefaultUI: true,
        noClear: true,
        navigationControl: true,
        navigationControlOptions: {
            position: google.maps.ControlPosition.TOP_LEFT,
            style: google.maps.NavigationControlStyle.DEFAULT
        },
        mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.DEFAULT,
            position: google.maps.ControlPosition.TOP_RIGHT,
            mapTypeIds: [
                    google.maps.MapTypeId.HYBRID,
                    google.maps.MapTypeId.ROADMAP,
                    google.maps.MapTypeId.SATELLITE]
        }
    };

    //兼容JQuery对象
    if (mapCanvas.get) {
        mapCanvas = mapCanvas.get(0);
    }
    return new google.maps.Map(mapCanvas, options);
}
/// <summary>
/// 自动定位我的位置，以Mark的形式和InfoWindow展示当前位置。异步操作！
/// 首先使用Google自己的定位方式。如果由于网络等原因Google未能定位成功，我们通过Ajax来访问IP数据库，定位当前用户的IP的数据库信息
/// </summary>
/// <param name="map" type="google.maps.Map">地图对象</param>
local.gmap.autoLocatePosition = function (map, showMarker, autoOpenInfoWindow) {
    var initialLocation;
    var beijing = new google.maps.LatLng(39.928901672363, 116.38829803467);
    var browserSupportFlag = new Boolean();

    // Try W3C Geolocation (Preferred)
    if (navigator.geolocation) {
        browserSupportFlag = true;
        navigator.geolocation.getCurrentPosition(function (position) {
            initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            addMarker(initialLocation);
            map.setCenter(initialLocation);
        }, function () {
            handleNoGeolocation(browserSupportFlag);
        });
        // Try Google Gears Geolocation
    } else if (google.gears) {
        browserSupportFlag = true;

        var geo = google.gears.factory.create('beta.geolocation');
        geo.getCurrentPosition(function (position) {
            initialLocation = new google.maps.LatLng(position.latitude, position.longitude);
            addMarker(initialLocation);
            map.setCenter(initialLocation);
        }, function () {
            handleNoGeoLocation(browserSupportFlag);
        });
        // Browser doesn't support Geolocation
    } else {
        browserSupportFlag = false;
        handleNoGeolocation(browserSupportFlag);
    }

    //nested function ,called automatically when google's geolocation failed
    function handleNoGeolocation(errorFlag) {
        var ipAddr = CommAjaxHelper.GetIPLocationInfo().value;
        if (ipAddr != null && ipAddr.length > 0) {
            local.gmap.searchByAddr(map, ipAddr.split(',')[0]);
            return;
        }
        //        if (errorFlag == true) {
        //            alert("Geolocation service failed.");
        //            initialLocation = beijing;
        //        } else {
        //            alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
        //            initialLocation = beijing;
        //        }
        map.setCenter(initialLocation);
    }

    //nested function for creating marker of current pos 
    function addMarker(location) {

        local.gmap.searchByLatLon(location.lat(), location.lng(), function (exeStatus, orgLocation, geoResults) {
            var formattedAddr = '不知道。';
            if (exeStatus) {
                location = geoResults[0].geometry.location;
                formattedAddr = geoResults[0].formatted_address;
            }
            if (!showMarker) {
                return;
            }

            var infoContent = local.gmap.createPosInfoContent(location, geoResults[0].formatted_address, false, true);

            map.autoLocatePositionMarker = local.gmap.addMarker(map, location, "偷乐网猜测您的当前位置", infoContent);
            if (autoOpenInfoWindow) {
                map.autoLocatePositionMarker.infoWindow.open(map, map.autoLocatePositionMarker);
            }
        });
    }
}

/// <summary>生成位置信息的HTML代码</summary>
/// <param name="location" type="LatLng">经纬度对象</param>
/// <param name="formattedAddr" type="string">格式化过的地址字符串</param>
/// <returns type="String" />
local.gmap.createPosInfoContent = function (location, formattedAddr, showLatLng, editable) {
    if (formattedAddr.substring(0, 2) == "中国") {
        formattedAddr = formattedAddr.substring(2);
    }
    if (formattedAddr.indexOf(' ')) {
        formattedAddr = formattedAddr.split(' ')[0];
    }
    var result = '<div class="infoWindowContainer">' +
            '<b>我的方位信息:</b> <br>';

    if (showLatLng) {
        result += '<label>纬度：' + location.lat().toString().substring(0, 10) + '， 经度：'
                + location.lng().toString().substring(0, 10) + '</label><br>';
    }
    if (editable) {
        result += '<input type="text" name="detailAddr" class="detailAddr" title="如果您觉得我们显示的位置不准确，请修正一下吧！" value="' + formattedAddr + '" /><br>';
    }
    else {
        result += '<label>' + formattedAddr + '</label><br>';
    }
    result += '</div>';
    return result;
}

/// <summary>搜索给定的地址，并将最符合的以marker形式在地图上显示出来</summary>
/// <param name="mapObject" type="google.maps.Map">地图对象</param>
/// <param name="address" type="string">地址字符串</param>
local.gmap.searchByAddr = function (mapObject, address) {
    var geocoderRequest = {
        address: address,
        region: "cn"
    };
    var geocoder = local.gmap.getGeocoder();
    geocoder.geocode(geocoderRequest, function (results, status) {
        // Code that will handle the response 
        // Check if status is OK before proceeding 
        if (status == google.maps.GeocoderStatus.OK) {
            // Do something with the response 
            // Center the map on the returned location 
            mapObject.setCenter(results[0].geometry.location);
            var infoContent = local.gmap.createPosInfoContent(results[0].geometry.location, results[0].formatted_address);
            mapObject.autoLocatePositionMarker = local.gmap.addMarker(mapObject, results[0].geometry.location, results[0].formatted_address, infoContent);
            mapObject.autoLocatePositionMarker.infoWindow.open(mapObject, mapObject.autoLocatePositionMarker);
        }
        else {
            alert("搜索失败!");
        }
    });
}
/// <summary>搜索给定的地址，并将最符合的以marker形式在地图上显示出来</summary>
/// <param name="mapObject" type="google.maps.Map">地图对象</param>
/// <param name="address" type="string">地址字符串</param>
local.gmap.searchAllRelatedByAddr = function (mapObject, address) {
    var geocoderRequest = {
        address: address,
        region: "cn"
    };
    var geocoder = local.gmap.getGeocoder();
    geocoder.geocode(geocoderRequest, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            //            mapObject.setCenter(results[0].geometry.location);
            jQuery.each(results, function (i, perResult) {
                var infoContent = local.gmap.createPosInfoContent(perResult.geometry.location, perResult.formatted_address);
                local.gmap.addMarker(mapObject, perResult.geometry.location, perResult.formatted_address, infoContent);
            });
            local.gmap.fitMarkerBounds(mapObject);
        }
        else {
            alert("搜索失败!");
        }
    });
}
/// <summary>获得当前正在打开的InfoWIndow</summary>
local.gmap.getCurrentOpenInfoWindow = function (mapObject) {
    return mapObject.openInfoWindow;
}
/// <summary>获得当前地图对象上的所有Marker</summary>
local.gmap.getMarkers = function (mapObject) {
    return mapObject._markers;
}
/// <summary>根据当前地图上的markers自适应地图窗口大小和Zoom</summary>
local.gmap.fitMarkerBounds = function (mapObject) {
    if (!local.gmap.getMarkers(mapObject)) {
        return;
    }
    if (local.gmap.getMarkers(mapObject).length == 1) {
        var marker = local.gmap.getMarkers(mapObject)[0];
        mapObject.setCenter(marker.getPosition());
        return;
    }
    var maxLon = 0;
    var minLon = 0;

    var maxLat = 0;
    var minLat = 0;

    jQuery.each(local.gmap.getMarkers(mapObject), function (i, marker) {
        if (i == 0) {
            maxLon = minLon = marker.getPosition().lng();
            maxLat = minLat = marker.getPosition().lat();
        }
        else {
            if (marker.getPosition().lng() > maxLon) {
                maxLon = marker.getPosition().lng();
            }
            if (marker.getPosition().lng() < minLon) {
                minLon = marker.getPosition().lng();
            }
            if (marker.getPosition().lat() > maxLat) {
                maxLat = marker.getPosition().lat();
            }
            if (marker.getPosition().lat() < minLat) {
                minLat = marker.getPosition().lat();
            }
        }
    });
    //东北
    var ne = new google.maps.LatLng(maxLat, maxLon);
    //西南
    var sw = new google.maps.LatLng(minLat, minLon);

    var latLngBounds = new google.maps.LatLngBounds(sw, ne);
    //    mapObject.setCenter(latLngBounds.getCenter());
    mapObject.fitBounds(latLngBounds);
}
/// <summary>为一个Marker添加InfoWindow信息</summary>
local.gmap.addInfoWindow = function (mapObject, marker, clickContent) {
    if (clickContent.get) {
        clickContent = clickContent.get(0);
    }
    var infowindow = new google.maps.InfoWindow({
        content: clickContent,
        zIndex:1200
    });
    marker.infoWindow = infowindow;
    infowindow.marker = marker;
    google.maps.event.addListener(marker, 'click', function () {

        if (mapObject.openInfoWindow != null && mapObject.openInfoWindow != infowindow) {
            mapObject.openInfoWindow.close();
        }

        mapObject.openInfoWindow = infowindow;
        infowindow.open(mapObject, marker);
    });
}

/// <summary>弹出一个marker的InfoWindow</summary>
local.gmap.openInfoWindow = function (marker) {
    if (marker.infoWindow) {
        marker.getMap().openInfoWindow = marker.infoWindow;
        marker.infoWindow.open(marker.getMap(), marker);
    }
}
/// <summary>清除该地图上的所有marker</summary>
local.gmap.clearMarkers = function (mapObject) {
    if (mapObject._markers) {
        while (mapObject._markers.length > 0) {
            mapObject._markers.shift().setMap(null);
        }
    }
}

/// <summary>清除一个marker对象</summary>
local.gmap.removeMarker = function (marker) {
    var mapObject = marker.getMap();
    if (mapObject._markers) {
        var index = jQuery.inArray(marker, mapObject._markers);
        if (index >= 0) {
            mapObject._markers.splice(index, 1);
        }
    }
    marker.setMap(null);
}

/// <summary>在当前地图上添加一个Marker，如果ClickContent为空，则没有infoWindow;否则自动生成一个InfoWindow</summary>
local.gmap.addMarker = function (mapObject, location, tipsTitle, clickContent) {

    var marker = new google.maps.Marker({
        map: mapObject,
        position: location,
        title: tipsTitle
    });

    if (!mapObject._markers) {
        mapObject._markers = new Array();
    }

    mapObject._markers.push(marker);

    if (clickContent && clickContent.length > 0) {
        local.gmap.addInfoWindow(mapObject, marker, clickContent);
    }

    return marker;
}

// 私有静态缓存对象，缓存一个Geocoder对象
local.gmap._geocoder = null;
/// <summary>获得一个Geocoder对象</summary>
local.gmap.getGeocoder = function () {
    if (!local.gmap._geocoder)
        local.gmap._geocoder = new google.maps.Geocoder();

    return local.gmap._geocoder;
}

/// <summary>按照经纬度反向地址解析</summary>
/// <param name="lat" type="float">纬度</param>
/// <param name="lng" type="float">经度</param>
/// <param name="callback" type="function">
/// 回调函数,三个参数：
/// 第一个参数表示执行状态，1为成功，0代表失败
/// 第二一个参数表示原始的经纬度
/// 第三个参数表示geocoder返回的GeocoderResults 对象
/// </param>
/// <returns type="viod" />
local.gmap.searchByLatLon = function (lat, lng, callback) {
    var latlng = new google.maps.LatLng(lat, lng);
    var geocoder = local.gmap.getGeocoder();
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results) {
                callback(1, latlng, results);
            }
        } else {
            alert("Geocoder failed due to: " + status);
            callback(0, latlng, null);
        }
    });
}
/// 当需要标注时，markMapOpt为1，不需要标注时则markMapOpt非1
local.gmap.createMapContainer = function (markMapOpt) {
    if (markMapOpt == 1) {
        var html = '<div class="updatePostionMapContainer"><div style="height: 100%; width: 100%;"></div>'
            + '<div class="toolbar ui-widget-content ui-corner-all">'
            + '<button>开始标注</button><input type="text"/><button>搜索</button>'
            + '</div></div>';
    }
    else {
        var html = '<div class="updatePostionMapContainer"><div style="height: 100%; width: 100%;"></div>'
            + '<div class="toolbar ui-widget-content ui-corner-all">'
            + '</div></div>';
    }
    return $(html);
}
    local.gmap.popUpzoomOutMap = function (currentPosition) {
        var popupMapControl = null;
        popupMapControl = local.gmap._popUpzoomOutMapIntance = local.gmap.createMapContainer(0);
        var toolbarControl = popupMapControl.children(":last");

        popupMapControl
            .dialog({
                //autoOpen: true,
                title: '放大地图',
                show: 'slide',
                width: 700,
                height: 600,
                modal: true,
                closeText: '关闭'
            }).dialog("open");
       var gisShow_Map = local.gmap.createMap(popupMapControl.children(":first"), currentPosition);
    }
local.gmap.showPopupMapChooser = function (currentPosition) {
    var popupMapControl = null;
    popupMapControl = local.gmap._popupMapChooserIntance = local.gmap.createMapContainer(1); //.appendTo($(document.body));
    var toolbarControl = popupMapControl.children(":last");

    popupMapControl
            .dialog({
                //autoOpen: true,
                title: '在地图上找到你的位置',
                show: 'slide',
                width: 700,
                height: 600,
                modal: true,
                closeText: '关闭'
            }).dialog("open");
//    popupMapControl.css("z-index", "1200"); 
    var gisShow_Map = local.gmap.createMap(popupMapControl.children(":first"), currentPosition);
    var dragBtn = toolbarControl.children("button:first").button().click(dragEventHandler);
    if (currentPosition) {
        local.gmap.addMarker(gisShow_Map, currentPosition, "我的当前位置", '点击"开始拖动"按钮，拖动并修改您的位置！');
    }
    else {
        local.gmap.autoLocatePosition(gisShow_Map, true);
    }

    function dragEventHandler() {
        var buttonText = $(this).text().trim();
        alert(buttonText);
        if (buttonText == "开始标注") {
            //点击了开始拖动
            dragBtn.button("option", "label", "确认位置");
            var srcMarker = local.gmap.getMarkers(gisShow_Map)[0];

            var content = '<div style="min-height:100px;min-width:200px;">拖动图标，在地图上标注我的精确位置。<br>点击[停止拖动]，将此位置作为我的当前位置。</div>';

            var newMarker = local.gmap.addMarker(gisShow_Map, srcMarker.getPosition(), "我的新位置", content);

            newMarker.setIcon("/Web/images/comm/marker_green.png");
            var shadow = new google.maps.MarkerImage('/Web/images/comm/marker_shadow.png',
                  new google.maps.Size(29, 22),
                  new google.maps.Point(0, 0),
                  new google.maps.Point(0, 22));
            newMarker.setShadow(shadow);
            srcMarker.infoWindow.close();
            local.gmap.openInfoWindow(newMarker);
            newMarker.setDraggable(true);

            google.maps.event.addListener(newMarker, 'dragstart', function (mouseEvent) {
                newMarker.infoWindow.close();
            });

            google.maps.event.addListener(newMarker, 'dragend', function (mouseEvent) {
                var pos = mouseEvent.latLng;
                newMarker.getMap().panTo(pos);
                local.gmap.searchByLatLon(pos.lat(), pos.lng(), function (exeStatus, orgLocation, geoResults) {
                    var formattedAddr = '我们不知道你的位置。';
                    var location = orgLocation;
                    if (exeStatus) {
                        location = geoResults[0].geometry.location;
                        formattedAddr = geoResults[0].formatted_address;
                    }
                    var infoContent = $(local.gmap.createPosInfoContent(location, formattedAddr, false, true));

                    var useBtn = $("<button>").button({ label: "这是我的位置" });
                    useBtn.click(thisIsMyPos);

                    var notUseBtn = $("<button>").button({ label: "不是" });
                    notUseBtn.click(cancelDrag);
                    var iwToolbarControl = $("<div>").css("margin-top", "10px").append(useBtn).append(notUseBtn);

                    newMarker.infoWindow.setContent(infoContent.append(iwToolbarControl).get(0));

                    local._debugObject = newMarker.infoWindow.getContent();
                    local.gmap.openInfoWindow(newMarker);
                });
            });
        }
        else {
            thisIsMyPos();
        }
    }

    function thisIsMyPos() {
        dragBtn.button("option", "label", "开始标注");
        var srcMarker = local.gmap.getMarkers(gisShow_Map)[0];
        var newMarker = local.gmap.getMarkers(gisShow_Map)[1];
        srcMarker.setPosition(newMarker.getPosition());
        //        local._debugObject = newMarker.infoWindow.getContent();
        var infoContent = $(newMarker.infoWindow.getContent());
        infoContent.children(":last").remove();
        srcMarker.infoWindow.setContent(infoContent.get(0));
        local.gmap.removeMarker(newMarker);
        local.gmap.openInfoWindow(srcMarker);
    }
    function cancelDrag() {
        dragBtn.button("option", "label", "开始标注");
        var srcMarker = local.gmap.getMarkers(gisShow_Map)[0];
        var newMarker = local.gmap.getMarkers(gisShow_Map)[1];
        gisShow_Map.setCenter(srcMarker.getPosition());
        local.gmap.removeMarker(newMarker);
    }

    toolbarControl.children("button:last").button().click(function () {
        while (local.gmap.getMarkers(gisShow_Map).length > 1) {
            var markers = local.gmap.getMarkers(gisShow_Map);
            local.gmap.removeMarker(markers[markers.length - 1]);
        }

        //禁止按钮拖动
        dragBtn.button("option", "label", "开始标注").button("option", "disabled", true);
        var geocoderRequest = {
            address: $(this).prev("input").val(),
            region: "cn"
        };
        var geocoder = local.gmap.getGeocoder();
        geocoder.geocode(geocoderRequest, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                jQuery.each(results, function (i, perResult) {
                    var infoContent
                    = local.gmap.createPosInfoContent(perResult.geometry.location,
                    perResult.formatted_address, false, true);

                    var useBtn = $("<button>").button({ label: "这是我的位置" });
                    useBtn.click(function () {
                        var srcMarker = local.gmap.getMarkers(gisShow_Map)[0];
                        var newMarker = gisShow_Map.openInfoWindow.marker;

                        srcMarker.setPosition(newMarker.getPosition());

                        //设置内容
                        var infoContent = $(newMarker.infoWindow.getContent());
                        infoContent.children(":last").remove();

                        srcMarker.infoWindow.setContent(infoContent.get(0));

                        //删除其他的Marker
                        while (local.gmap.getMarkers(gisShow_Map).length > 1) {
                            var markers = local.gmap.getMarkers(gisShow_Map);
                            local.gmap.removeMarker(markers[markers.length - 1]);
                        }
                        local.gmap.openInfoWindow(srcMarker);

                        toolbarControl.children("button:first").button("option", "disabled", false).click(dragEventHandler);
                    });

                    var notUseBtn = $("<button>").button({ label: "不是" });
                    notUseBtn.click(function () {
                        //删除当前的Marker
                        var newMarker = local.gmap.getCurrentOpenInfoWindow(gisShow_Map).marker;
                        newMarker.infoWindow.close();
                        local.gmap.removeMarker(newMarker);
                        if (local.gmap.getMarkers(gisShow_Map).length == 2) {
                            toolbarControl.children("button:first").button("option", "disabled", false).click(dragEventHandler);
                        }
                    });
                    var iwToolbarControl = $("<div>").append(useBtn).append(notUseBtn);

                    var newMarker = local.gmap.addMarker(gisShow_Map, perResult.geometry.location, perResult.formatted_address, $(infoContent).append(iwToolbarControl));
                    newMarker.setIcon("/Web/images/comm/marker_green.png");
                    var shadow = new google.maps.MarkerImage('/Web/images/comm/marker_shadow.png',
                                  new google.maps.Size(29, 22),
                                  new google.maps.Point(0, 0),
                                  new google.maps.Point(0, 22));
                    newMarker.setShadow(shadow);
                });
                local.gmap.fitMarkerBounds(gisShow_Map);
            }
            else {
                alert("搜索失败!");
            }
        });
    });
}